package com.android.mi_temperature2_for_dilink;

import android.Manifest;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothGatt;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;

import com.android.mi_temperature2_for_dilink.databinding.ActivityMainBinding;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleReadCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.socks.library.KLog;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    private com.android.mi_temperature2_for_dilink.databinding.ActivityMainBinding mBinding;
    private BleDataHolder holder;
    private String last_device_address;
    private SharedPreferences mPreferences;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());
        holder = new BleDataHolder();
        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        last_device_address = mPreferences.getString(Constants.KEY_LAST_DEVICE_ADDRESS, "");
        String leftPadding = mPreferences.getString(Constants.KEY_PADDING_LEFT, "0");
        String topPadding = mPreferences.getString(Constants.KEY_PADDING_TOP, "0");
        boolean autoBoot = mPreferences.getBoolean(Constants.KEY_AUTO_BOOT_FLOATING, false);
        holder.setLastMac(last_device_address);
        holder.setLeftPadding(leftPadding);
        holder.setTopPadding(topPadding);
        holder.setAutoBoot(autoBoot);
        mBinding.setBleData(holder);

        mBinding.permissionCheckBtn.setOnClickListener(this);
        mBinding.setupBleDeviceBtn.setOnClickListener(this);
        mBinding.readBtn.setOnClickListener(this);
        mBinding.floatingTestBtn.setOnClickListener(this);
        mBinding.savePaddingBtn.setOnClickListener(this);
        mBinding.autoBootSw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mPreferences.edit()
                        .putBoolean(Constants.KEY_AUTO_BOOT_FLOATING, isChecked)
                        .apply();
            }
        });

        if (BleManager.getInstance().isSupportBle()) {
            KLog.e(TAG, "onCreate: 支持ble设备");
        } else {
            KLog.e(TAG, "onCreate: 不支持ble设备");
        }

        boolean fromFloating = getIntent().getBooleanExtra("fromFloating", false);
        if (!TextUtils.isEmpty(last_device_address) && !fromFloating) {
            BleManager.getInstance().disconnectAllDevice();
            Intent intent = new Intent(this, MyService.class);
            intent.putExtra("isBackground", false);
            startService(intent);
            finish();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.permission_check_btn) {
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                return;
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 0);
                return;
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
                return;
            }
            Toast.makeText(this, "所需权限均已授权", Toast.LENGTH_SHORT).show();
        } else if (viewId == R.id.setup_ble_device_btn) {
            if (!BleManager.getInstance().isBlueEnable()) {
                Toast.makeText(this, "蓝牙未打开", Toast.LENGTH_SHORT).show();
                return;
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "请先检查权限", Toast.LENGTH_SHORT).show();
                return;
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "请先检查权限", Toast.LENGTH_SHORT).show();
                return;
            }
            KLog.e("开始扫描ble设备");
            ProgressDialog pro = new ProgressDialog(this);
            pro.setMessage("ble设备扫描中。。。");
            BleManager.getInstance().scan(new BleScanCallback() {
                @Override
                public void onScanFinished(List<BleDevice> scanResultList) {
                    KLog.e(TAG, "onScanFinished: ");
                    pro.dismiss();

                    CharSequence[] items = new String[scanResultList.size()];
                    for (int i = 0; i < scanResultList.size(); i++) {
                        BleDevice bleDevice = scanResultList.get(i);
                        items[i] = bleDevice.getName() + "->" + bleDevice.getMac();
                    }
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("请选择要保存的BLE设备")
                            .setItems(items, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    KLog.e("which = " + which + " " + items[which]);
                                    BleDevice bleDevice = scanResultList.get(which);
                                    String mac = bleDevice.getMac();
                                    last_device_address = mac;
                                    PreferenceManager.getDefaultSharedPreferences(MainActivity.this)
                                            .edit()
                                            .putString(Constants.KEY_LAST_DEVICE_ADDRESS, mac)
                                            .apply();
                                    Toast.makeText(MainActivity.this, "BLE设备地址保存成功", Toast.LENGTH_SHORT).show();
                                }
                            })
                            .show();
                }

                @Override
                public void onScanStarted(boolean success) {
                    KLog.e(TAG, "onScanStarted: ");
                    pro.show();
                }

                @Override
                public void onScanning(BleDevice bleDevice) {
                    //onScanning: XL060210961AF9A2A5740AA094 10:96:1A:F9:A2:A5
                    //onScanning: LYWSD03MMC A4:C1:38:11:FF:CC
                    KLog.e(TAG, "onScanning: " + bleDevice.getName() + " " + bleDevice.getMac());
                }
            });
        } else if (viewId == R.id.floating_test_btn) {
            BleManager.getInstance().disconnectAllDevice();
            Intent in = new Intent(this, MyService.class);
            in.putExtra("isBackground", false);
            startService(in);
        } else if (viewId == R.id.read_btn) {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setMessage("设备连接中。。。");
            dialog.show();
            BleManager.getInstance().connect(last_device_address, new BleGattCallback() {
                @Override
                public void onStartConnect() {
                    KLog.e();
                }

                @Override
                public void onConnectFail(BleDevice bleDevice, BleException exception) {
                    KLog.e();
                    dialog.dismiss();
                    Toast.makeText(MainActivity.this, "蓝牙连接失败", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                    KLog.e();
                    dialog.setMessage("数据读取中。。。");
                    BleManager.getInstance().read(bleDevice, UuidUtil.MAIN_DATA_SRV, UuidUtil.MAIN_DATA_CH, new BleReadCallback() {
                        @Override
                        public void onReadSuccess(byte[] data) {
                            dialog.dismiss();
                            int[] parseData = parseData(data);
                            holder.setTemperature(parseData[0] + "");
                            holder.setHumidity(parseData[1] + "");
                            holder.setVoltage(parseData[2] + "");
                            mBinding.setBleData(holder);
                        }

                        @Override
                        public void onReadFailure(BleException exception) {
                            dialog.dismiss();
                            KLog.e();
                        }
                    });
                }

                @Override
                public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                    KLog.e();
                }
            });
        } else if (viewId == R.id.save_padding_btn) {
            String leftPadding = holder.getLeftPadding();
            String topPadding = holder.getTopPadding();
            mPreferences.edit()
                    .putString(Constants.KEY_PADDING_LEFT, leftPadding)
                    .putString(Constants.KEY_PADDING_TOP, topPadding)
                    .apply();
            Toast.makeText(this, "浮窗边距保存成功", Toast.LENGTH_SHORT).show();
        }
    }

    public static int[] parseData(byte[] data) {
        String hexStr = HexUtil.encodeHexStr(data);
        KLog.e("hex data = " + hexStr);
        int data1 = (data[0]) + ((data[1] & 0xff) << 8);
        int data2 = data[2] & 0xff;
        int data3 = (data[3] & 0xff) + ((data[4] & 0xff) << 8);
        KLog.e("温度 = " + data1 + ",湿度 = " + data2 + ",电压 = " + data3);
        return new int[]{data1, data2, data3};
    }
}